<?php
/**
 * Created by PhpStorm.
 * User: 835173372@qq.com
 * NickName: 孟老师
 * Date: 2017/2/12 22:57
 */

namespace app\app\controller;

use think\Request;
use think\Db;

class Member extends Base{

    public function index(){
        echo 'member-api';exit;
    }
    //发送短信操作
    public function send_sms(){
        $mobile = trim($_POST['mobile']);
        $smscode = mt_rand(1111,9999);
        $content = '短信验证码';
        $res = smsbao($smscode,$content,$mobile);
        if($res == 'ok'){
            ajaxmsg('发送成功',1);
        }else{
            ajaxmsg('发送失败',0);
        }
    }

    //注册接口
    public function reg(){

        $data['mobile_bind'] = 1;
        $data['mobile'] = trim($_POST['mobile']);
        $data['password'] = md5(trim($_POST['password']));
        //$data['code'] = trim($_POST['code']);//缺少验证码的验证

        $code = $_POST['code'];//APP端发送
        $smscode = session('smscode');
        if($code != $smscode){
            ajaxmsg('验证码不正确',0);
        }
        $data['create_time'] = time();
        $count = Db::name("member")->where("mobile='{$data['mobile']}'")->count();
        if($count > 0){
          ajaxmsg('此手机号被占用或已被注册',0);
        }else{
            $mid = Db::name('member')->insertGetId($data);
            if($mid > 0){
                //防止session污染
                session('smscode', null);
                session('smstime', null);
                session('mobile', null);
                ajaxmsg('注册成功，请登录',1);
            }else{
                ajaxmsg('注册失败',0);
            }
        }
    }

    //登录接口
    public function login(){
        $mobile = trim($_POST['mobile']);
        $password = md5(trim($_POST['password']));
        $deviceid = trim($_POST['deviceid']);
        $info = Db::name('member')->where("mobile='{$mobile}' and password={$password}")->find();
        if($info){
            $data['token'] = $this->create_token();
            $data['mid'] = $info['id'];
            $data['deviceid'] = $deviceid;
            $count = Db::name('token')->where("mid={$data['mid']}")->conut();
            if($count > 0){
                Db::name('token')->where("mid={$data['mid']}")->update(array('token'=>$data['token']));
            }else{
                Db::name('token')->insertGetId($data);
            }
            $info['token'] = $data['token'];
            ajaxmsg('登录成功',1,$info);
        }else{
            ajaxmsg('用户名或密码错误，重新提交',0);
        }

    }
}